import axios from 'axios'
import { Notification } from 'element-ui'
import router from '@/router/index'

// axios实例
const service = axios.create({
	baseURL: process.env.NODE_ENV == 'development' ? 'http://localhost:1233' : 'http://cyuw.top:1233',
	timeout: 60000,
	headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})

// 请求拦截器
service.interceptors.request.use(
	(config) => {
		const token = getToken()
		if (token != undefined && token != null && token != '') {
			config.headers['Access-Token'] = token
		}

		// 追加时间戳，防止GET请求缓存
		if (config.method?.toUpperCase() === 'GET') {
			config.params = { ...config.params, t: new Date().getTime() }
		}

		return config
	},
	error => {
		return Promise.reject(error)
	}
)

// 响应拦截器
service.interceptors.response.use(
	response => {
		if (response.status !== 200) {
			return Promise.reject(new Error(response.statusText || 'Error'))
		}
		if (response.headers['content-type'] === 'application/octet-stream') {
			return response
		}
		const res = response.data
		// 响应成功
		if (res.code === 200) {
			return res
		}

		// 错误提示
		Notification.error({
			title: '操作失败',
			message: res.msg,
			duration: 3000
		})

		// 没有权限，如：未登录、登录过期等，需要跳转到登录页
		if (res.code === 401) {
			setToken('')
			router.replace('/Featured', () => {
				location.reload()
			})
		}

		return Promise.reject(new Error(res.msg || 'Error'))
	},
	error => {
		Notification.error({
			title: '操作失败',
			message: res.msg,
			duration: 3000
		})
		return Promise.reject(error)
	}
)

export const getToken = () => {
	try {
		return window.localStorage.getItem('token')
	} catch (err) {
		setToken('')
		return ''
	}
}

export const setToken = (value) => {
	window.localStorage.setItem('token', value)
}

export const getSync = (path) => {
	return service.get(path)
}

export const postSync = (path, data) => {
	return service.post(path, data, {
		headers: {
			'Content-Type': 'application/json;charset=UTF-8'
		}
	})
}